﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Reflection;
using System.Text;

namespace com.sddemo.controls.src
{
    public static class EnumUtil
    {
        #region FetchDescription 
        /// <summary> 
        /// 获取枚举值的描述文本 
        /// </summary> 
        /// <param name="value"></param> 
        /// <returns></returns> 
        public static string FetchDescription(this Enum value)
        {
            FieldInfo fi = value.GetType().GetField(value.ToString());
            DescriptionAttribute[] attributes =
               (DescriptionAttribute[])fi.GetCustomAttributes(
               typeof(DescriptionAttribute), false);
            return (attributes.Length > 0) ? attributes[0].Description : value.ToString();
        }
        #endregion

        /// <summary>
        /// 枚举转列表
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <returns>IList<EnumEntity></returns>
        public static IList<EnumEntity> EnumToList<T>()
        {
            IList<EnumEntity> list = new List<EnumEntity>();
            foreach (var item in Enum.GetValues(typeof(T)))
            {
                EnumEntity enumEntity = new EnumEntity();
                Object[] objArr = item.GetType().GetField(item.ToString()).GetCustomAttributes(typeof(DescriptionAttribute), true);
                if (objArr != null && objArr.Length > 0)
                {
                    DescriptionAttribute descAttr = objArr[0] as DescriptionAttribute;
                    enumEntity.Text = descAttr.Description;
                }
                enumEntity.Value = Convert.ToInt32(item);
                enumEntity.Name = item.ToString();
                list.Add(enumEntity);
            }
            return list;
        }
    }

}
